import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/utils/file_preview_util.dart';
import 'package:kq_flutter_core_widget/utils/native/file_picker_native_util.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_core_widget/widgets/imageBox/kq_image_box.dart';
import 'package:kq_flutter_widgets/widgets/formItem/entity/kq_form_entity.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import '../../config/kq_global.dart';
import '../../resources/kq_images.dart';
import '../../theme/kq_theme_manager.dart';
import '../dialog/kq_file_picker.dart';

class KqHeadImageView extends StatefulWidget {
  const KqHeadImageView({
    super.key,
    this.iconSize = 80,
    required this.defaultUrl,
    required this.entity,
    this.backgroundUrl,
    this.gradient,
    this.space = 10,
    this.isCircle = false,
    this.isOriginal = false,
    this.height,
    this.txtColor = KqThemeColors.text26,
    this.didSelected,
  });

  //展示文本
  final KqFormEntity entity;

  //背景图片
  final String? backgroundUrl;

  //默认展示的
  final ImageUrl defaultUrl;

  //图片大小 默认图的
  final double iconSize;

  //上传的图片和文本展示之间的间隔
  final double space;

  //文本颜色
  final Color txtColor;

  //是否需要切割成圆角 默认图
  final bool isCircle;

  //网络图展示在原有的上面
  final bool isOriginal;

  //高度
  final double? height;

  //背景色
  final Gradient? gradient;

  //上传图片
  final Function(KqFile file)? didSelected;

  @override
  State<KqHeadImageView> createState() => _KqHeadImageViewState();
}

class _KqHeadImageViewState extends State<KqHeadImageView> {
  // 放大图片
  void handlePreview(ImageUrl? imgUrl) {
    FilePreviewUtil.previewSingleImg(imgUrl!);
  }

  //上传
  void handleUpload() {
    KqFilePicker().choosePhoto(context, ((files) {
      KqFile xfile = files.first;
      if (widget.didSelected != null) {
        widget.didSelected!(xfile);
      }
    }));
  }

  //展示网络上获取的
  Widget renderNetwork() {
    ImageUrl? netUrl;
    if (widget.entity.imageUrls != null &&
        widget.entity.imageUrls!.isNotEmpty) {
      netUrl = widget.entity.imageUrls![0];
    }
    return ConstrainedBox(
      constraints: const BoxConstraints.expand(),
      child: Stack(
        children: [
          KqInkWell(
              onTap: () {
                //不允许编辑放大图片
                if (widget.entity.editable) {
                  handleUpload();
                } else {
                  handlePreview(netUrl!);
                }
              },
              child: Container(
                  color: KqThemeColors.bgF4,
                  height: widget.height ?? 200.r,
                  alignment: Alignment.center,
                  child: renderNetIcon(netUrl!))),
          Visibility(
              visible: widget.entity.editable,
              child: Positioned(
                  right: -1, //偏移点，要不然会有边
                  top: -1,
                  child: InkWell(
                      onTap: () {
                        //删除
                        setState(() {
                          netUrl = null;
                          widget.entity.imageUrls = [];
                        });
                      },
                      child: SizedBox(
                        width: 40.r,
                        height: 40.r,
                        child: KqImage.assets(
                          fit: BoxFit.contain,
                          url: KqImages.commonIcDelete,
                          package: KqGlobal.packageName,
                        ),
                      ))))
        ],
      ),
    );
  }

  Widget renderNetIcon(ImageUrl imageUrl) {
    return KqImage.custom(
      imageType: imageUrl.imageType,
      fit: BoxFit.fitHeight,
      url: imageUrl.url,
      width: KqScreenUtil().screenWidth,
      height: widget.height ?? 200.r,
      placeHolder: widget.defaultUrl.url,
      errorImage: widget.defaultUrl.url,
    );
  }

  Widget renderIcon(ImageUrl imgUrl) {
    return KqImage.custom(
      imageType: imgUrl.imageType,
      fit: BoxFit.cover,
      url: imgUrl.url,
      width: widget.iconSize,
      height: widget.iconSize,
      radius: widget.isCircle ? widget.iconSize / 2.0 : 0,
      placeHolder: widget.defaultUrl.url,
      errorImage: widget.defaultUrl.url,
    );
  }

  //展示默认的图片
  Widget renderNormal() {
    ImageUrl? netUrl;
    if (widget.entity.imageUrls != null &&
        widget.entity.imageUrls!.isNotEmpty) {
      netUrl = widget.entity.imageUrls![0];
    }
    return ConstrainedBox(
      constraints: const BoxConstraints.expand(),
      child: KqInkWell(
          onTap: () {
            //点击上传
            if (widget.entity.editable) {
              handleUpload();
            } else {
              ImageUrl? tmp = widget.isOriginal && netUrl != null
                  ? netUrl
                  : ImageUrl(imageType: ImageType.oss, url: '');
              handlePreview(tmp);
            }
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            children: [
              widget.isOriginal && netUrl != null
                  ? renderIcon(netUrl)
                  : renderIcon(widget.defaultUrl),
              Visibility(
                  visible: widget.entity.editable,
                  child: Container(
                    padding: EdgeInsets.only(top: widget.space),
                    child: Text(
                      widget.entity.title,
                      style: TextStyle(
                          color: widget.txtColor,
                          fontSize: KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .titleFontSize ??
                              16.sp),
                    ),
                  )),
            ],
          )),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: widget.height ?? 200.r,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: KqThemeColors.bgF4,
        gradient: widget.gradient,
        image: widget.backgroundUrl != null
            ? DecorationImage(
                fit: BoxFit.cover, image: AssetImage(widget.backgroundUrl!))
            : null,
      ),
      child: widget.isOriginal
          ? renderNormal()
          : (widget.entity.imageUrls != null &&
                  widget.entity.imageUrls!.isNotEmpty)
              ? renderNetwork()
              : renderNormal(),
    );
  }
}
